<?php

namespace app\common\util\map;


use app\common\util\Result;
use GuzzleHttp\Client;

class QQMapServer
{
    const key = "R3NBZ-ERSW4-N24U7-X5MTG-ZCE73-6LBE7";

    public static function searchAddress(string $keyword)
    {
        $key = self::key;
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?address=$keyword&key=$key";
        $clent = new Client();
        $request = $clent->get($url);
        $content = $request->getBody()->getContents();
        $contentJson = json_decode($content, true);
        if ($contentJson['status'] != 0) {
            return Result::failed($contentJson['status'], $contentJson['message']);
        }
        $address = [
            "lat" => $contentJson["result"]["location"]["lat"],
            "lng" => $contentJson["result"]["location"]["lng"],
            "res" => $contentJson
        ];
        return Result::success($address);
    }

    /**
     * 腾讯地图地址逆解析
     * @param $lat
     * @param $lng
     * @return Result
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function getAddressByLngLat($lat, $lng)
    {
        $key = self::key;
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=$lat,$lng&key=$key";
        $clent = new Client();
        $request = $clent->get($url);
        $content = $request->getBody()->getContents();
        $contentJson = json_decode($content, true);
        if ($contentJson['status'] != 0) {
            return Result::failed($contentJson['status'], $contentJson['message']);
        }
        $address = [
            "address" => $contentJson['result']['address'],
            "recommend" => $contentJson['result']['address'],
        ];
        if (array_key_exists("result", $contentJson) && array_key_exists("formatted_addresses", $contentJson["result"]) && array_key_exists("recommend", $contentJson["result"]["formatted_addresses"])) {
            $address["recommend"] = $contentJson["result"]["formatted_addresses"]["recommend"];
        }


        return Result::success($address);
    }

}